package cn.ylz.ylmall.account.controller;

import cn.ylz.ylmall.account.pojo.param.UserRegParam;
import cn.ylz.ylmall.account.pojo.param.UserUpdateParam;
import cn.ylz.ylmall.account.pojo.vo.*;
import cn.ylz.ylmall.account.security.CurrentPrincipal;
import cn.ylz.ylmall.common.ex.ServiceException;
import cn.ylz.ylmall.common.util.MailUtils;
import cn.ylz.ylmall.common.util.VerifyCode;
import cn.ylz.ylmall.common.web.JsonResult;
import cn.ylz.ylmall.account.pojo.param.UserLoginParam;
import cn.ylz.ylmall.account.pojo.param.UserRegParamAdmin;
import cn.ylz.ylmall.account.service.IUserService;
import cn.ylz.ylmall.common.web.ServiceCode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/v1/users/")
@Api(tags = "1.1. 账号管理-用户管理")
@Slf4j
@Validated
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private Producer checkCode;

    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    @ApiOperationSupport(order = 1)
    public JsonResult login(@Validated UserLoginParam userLoginParam, HttpServletRequest req, HttpServletResponse resp) {
        UserLoginResultVO loginResultVO = userService.login(userLoginParam, req, resp);
        return JsonResult.ok(loginResultVO);
    }

    @PostMapping("/logout")
    @ApiOperation("用户退出登录")
    @ApiOperationSupport(order = 100)
    public JsonResult logout() {
        SecurityContextHolder.clearContext();
        return JsonResult.ok();
    }

    @PostMapping("admin_reg")
    @ApiOperation("管理员注册")
    @PreAuthorize("hasAuthority('/account/user/add-new')")
    @ApiOperationSupport(order = 2)
    public JsonResult reg(@Valid UserRegParamAdmin userRegParam) {
        userService.reg(userRegParam);
        return JsonResult.ok();
    }

    @PostMapping("reg")
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 3)
    public JsonResult reg(@Valid UserRegParam userRegParam) {
        userService.regUser(userRegParam);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/delete")
    @PreAuthorize("hasAuthority('/account/user/delete')")
    @ApiOperation("根据ID删除用户")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult delete(@PathVariable @Range(min = 1, message = "请提交有效的用户ID值！") Long id) {
        userService.delete(id);
        return JsonResult.ok();
    }

    @ApiOperation("根据ID查询用户")
    @ApiOperationSupport(order = 15)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    @GetMapping("/{id:[0-9]+}")
    @PreAuthorize("hasAuthority('/account/user/read')")
    public JsonResult getStandardById(@PathVariable @Range(min = 1, message = "获取用户详情失败，请提交合法的ID值！") Long id) {
        log.debug("开始处理【根据ID查询用户】的请求，参数：{}", id);
        UserStandardVO userStandardVO = userService.getStandardById(id);
        return JsonResult.ok(userStandardVO);
    }

    @ApiOperation("修改个人信息")
    @ApiOperationSupport(order = 5)
    @PostMapping("/{id:[0-9]+}/update")
    @PreAuthorize("hasAuthority('/account/user/update')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult update(@PathVariable Long id, @Valid UserUpdateParam userUpdateParam, @ApiIgnore @AuthenticationPrincipal CurrentPrincipal currentPrincipal) {
        userService.update(id, userUpdateParam, currentPrincipal);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/enable")
    @PreAuthorize("hasAuthority('/account/user/update')")
    @ApiOperation("启用用户")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult setEnable(@PathVariable Long id) {
        userService.setEnable(id);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/disable")
    @PreAuthorize("hasAuthority('/account/user/update')")
    @ApiOperation("禁用用户")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "long")
    })
    public JsonResult setDisable(@PathVariable Long id) {
        userService.setDisable(id);
        return JsonResult.ok();
    }


    @GetMapping("AdminList")
    @ApiOperationSupport(order = 8)
    @PreAuthorize("hasAuthority('/account/user/read')")
    @ApiOperation("查询管理员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", dataType = "long")
    })
    public JsonResult list(Integer page) {
        log.debug("开始处理【查询管理员列表】的请求，页码：{}", page);
        Integer pageNum = page == null ? 1 : page;
        PageData<UserListItemVO> pageData = userService.listAdmin(pageNum);
        return JsonResult.ok(pageData);
    }

    @GetMapping("/list")
    @ApiOperationSupport(order = 9)
    @PreAuthorize("hasAuthority('/account/user/read')")
    @ApiOperation("查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", dataType = "long")
    })
    public JsonResult listUser(Integer page) {
        log.debug("开始处理【查询用户列表】的请求，页码：{}", page);
        Integer pageNum = page == null ? 1 : page;
        PageData<UserListItemVO> pageData = userService.list(pageNum);
        return JsonResult.ok(pageData);
    }

    @GetMapping("/{userId:[0-9]+}/role")
    @ApiOperation("根据ID查询用户的所有角色")
    @PreAuthorize("hasAuthority('/account/role/read')")
    @ApiOperationSupport(order = 10)
    public JsonResult listRoles(@PathVariable @Range(min = 1, message = "请提交有效的用户ID值！") Long userId) {
        List<UserRoleVO> list = userService.rolesById(userId);
        return JsonResult.ok(list);
    }

    @GetMapping("/{userId:[0-9]+}/permission")
    @ApiOperation("根据ID查询用户的所有权限")
    @PreAuthorize("hasAuthority('/account/user/read')")
    @ApiOperationSupport(order = 11)
    public JsonResult userInfo(@PathVariable @Range(min = 1, message = "请提交有效的用户ID值！") Long userId) {
        List<UserPermissionVO> list = userService.PermissionsById(userId);
        return JsonResult.ok(list);
    }

    @GetMapping("")
    @ApiOperation("获取当前登录用户的信息")
    @PreAuthorize("hasAuthority('/account/permission/read')")
    @ApiOperationSupport(order = 16)
    public JsonResult listPermissions(@ApiIgnore @AuthenticationPrincipal CurrentPrincipal principal) {
        UserStandardVO userStandardVO = userService.getStandardById(principal.getId());
        return JsonResult.ok(userStandardVO);
    }


    /*@GetMapping(value = "/verifyCode")
    @ApiOperation("登录验证码生成接口")
    public void verfyCode(HttpSession session, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        VerifyCode code = new VerifyCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        log.debug("当前登录验证码,{}",text);
        session.setAttribute("verify_code", text);
        VerifyCode.output(image, response.getOutputStream());
    }*/

    @GetMapping("/email")
    @ApiOperation("邮箱验证码生成接口")
    public JsonResult sendEmail(String email) {
        if (email.isEmpty()) {
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, "邮箱不能为空！");
        }
        mailUtils.sendMail(email);
        return JsonResult.ok();
    }


}
